package io.dirac.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.dirac.entity.OrderDetail;
import io.dirac.entity.OrderSurvey;
import io.dirac.entity.Product;
import io.dirac.entity.User;
import io.dirac.result.Result;
import io.dirac.service.OrderDetailService;
import io.dirac.service.OrderSurveyService;
import io.dirac.service.ProductService;
import io.dirac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Dirac
 * @since 2021-04-14
 */
@RestController
@RequestMapping("/order-survey")
public class OrderSurveyController {

    @Autowired
    private OrderSurveyService orderSurveyService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @PostMapping
    public Result add(@Validated @RequestBody OrderSurvey orderSurvey) {
        orderSurveyService.save(orderSurvey);
        return Result.success(orderSurvey.getId());
    }

    @PutMapping("/pay/{orderId}")
    public Result pay(@PathVariable(value = "orderId") Long orderId) {
        OrderSurvey orderSurvey = orderSurveyService.getById(orderId);

        List<OrderDetail> orderDetails = orderDetailService.getByOrderId(orderId);
        for (OrderDetail orderDetail : orderDetails) {
            Long productId = orderDetail.getProductId();
            BigDecimal purchaseQuantity = orderDetail.getPurchaseQuantity();

            Product product = productService.getById(productId);
            BigDecimal stock = product.getStock();
            BigDecimal newStock = stock.subtract(purchaseQuantity);
            product.setStock(newStock);
            productService.saveOrUpdate(product);

            System.out.println(orderDetail);
        }


        BigDecimal paymentAmount = orderSurvey.getPaymentAmount();
        BigDecimal discount = orderSurvey.getDiscount();  // WARNING: here need to modify when strategy change.
        BigDecimal scoreUsed = discount.multiply(BigDecimal.valueOf(100));

//        BigDecimal score = paymentAmount.divide(new BigDecimal("10.0"), RoundingMode.FLOOR);  // 花 10 块钱积 1 分
        BigDecimal score = paymentAmount;  // 花 1 块钱积 1 分

        Long userId = orderSurvey.getUserId();
        userService.decreaseScore(userId, scoreUsed);

        userService.increaseScore(userId, score);
        System.out.println(score);

        UpdateWrapper<OrderSurvey> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", orderId);
        wrapper.set("status", "已支付");
        orderSurveyService.update(wrapper);

        User user = userService.getById(userId);
        return Result.success(user);
    }
}
